require("common")
require("task")
require("layout")

plugin = {
	new = function(owner)
		local self = { stoicheia = owner, items = {} }
		setmetatable(self, { __index = plugin })
		return self
	end,
	
	traverseAll = function(self, handler)
		for i, name in pairs(common.getConfig("plugins")) do
			local item = self.items[name]
			local conf = common.getConfig("plugin." .. name)
			handler(name, item, conf)
		end
	end,
	
	traverse = function(self, handler)
		self:traverseAll(function(name, item, conf)
			if item then handler(name, item, conf) end
		end)
	end,
	
	loadAll = function(self)
		assert(self)
		self:traverseAll(function(name)
			log("plugin", "Initializing plugin `%s'", name)
			require("plugin." .. name)
			assert(plugin[name], "Plugin did not initialize")
			self.items[name] = plugin[name].new(self)
		end)
	end,
	
	activate = function(self, name)
		self.current = self.items[name]
		assert(self.current)
		self.current:activate()
	end,
	
	deactivate = function(self)
		if self.current == nil then return end
		if self.current.deactivate then
			self.current:deactivate()
		end
		self.current = nil
	end,
	
	destroy = function(self)
		assert(self)
		self:traverse(function(name, item)
			if item.destroy ~= nil then
				log("plugin", "Destroying plugin `%s'", name)
				item:destroy()
			end
		end)
	end,
	
	check = function(self)
		self:traverse(function(name, item)
			if item.check ~= nil then
				log("plugin", "Checking prerequisities of plugin `%s'", name)
				item:check()
			end
		end)
	end
}


